package com.kuaihaowei.configuration;

import com.kuaihaowei.Receiver;
import com.kuaihaowei.content.MqContant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by andy on 7/9/15.
 */
@Configuration
public class MqConfig {


    @Bean
    Queue queueOp() {
        return new Queue(MqContant.QUEUE_OP, false, false, false);
    }
    @Bean
    DirectExchange exchangeOp() {
        return new DirectExchange(MqContant.EXCHANGE_OP, false, false);
    }

    @Bean
    Queue queueMsg() {
        return new Queue(MqContant.QUEUE_MSG, false, false, false);
    }
    @Bean
    DirectExchange exchangeMsg() {
        return new DirectExchange(MqContant.EXCHANGE_MSG, false, false);
    }


    // op msg
    @Bean
    Binding bindingOp() {
        return BindingBuilder
                .bind(queueOp())
                .to(exchangeOp())
                .with(MqContant.QUEUE_OP);
    }

    // coupon task
    @Bean
    Binding bindingMsg() {
        return BindingBuilder
                .bind(queueMsg())
                .to(exchangeMsg())
                .with(MqContant.QUEUE_MSG);
    }


    // sender config
    @Bean
    RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

    // consumer config

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        MessageListenerAdapter adapter = new MessageListenerAdapter(receiver, "message");
        adapter.setMessageConverter(new Jackson2JsonMessageConverter());    // fastjson 只能解析静态内部类
        return adapter;
    }

    @Bean
    public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter adapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(MqContant.QUEUE_MSG, MqContant.QUEUE_OP);
        container.setQueues(queueMsg(), queueOp());
        container.setMessageListener(adapter);
        container.setConcurrentConsumers(16);
        return container;
    }
}
